//
//  OAApprovalDetailViewController.m
//  ERP
//
//  Created by goldeney on 15/3/25.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OAApprovalDetailViewController.h"

#import "OAApprovalDetailViewCell.h"
#import "AutoTextTableViewCell.h"
#import "DownFileInfoCell.h"
#import "NSString+handle.h"

#import "NSDictionary+DataFormat.h"
#import "NSString+handle.h"
#import "ServiceConnect.h"
#import "FileTypeIcon.h"
#import "DownLoadHandle.h"
#import "PreviewFileHelper.h"

#import "TYMActivityIndicatorView.h"
#import "OAReadApplyHtmlViewController.h"
#import "OAApprovalSubmitViewController.h"
#import "NSKeyedArchiverUserLogin.h"

#import "WebServiceCommonRequest.h"
#import "UITableView+Custom.h"

#define PIE_HEIGHT 230

@interface OAApprovalDetailViewController ()

@property (nonatomic,strong) NSDictionary *approvalBaseInfo;
@property (nonatomic,strong) NSMutableArray *approvalData;
@property (nonatomic,strong) NSMutableArray *appleModeData;

@property (nonatomic,strong) NSArray *orderData;
@property (nonatomic,assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功
@property (nonatomic,assign) NSInteger appleContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@property (nonatomic, assign) NSInteger viewType;//页面类型 1、我的申请 2、我的审批 3、所有审批
@property (nonatomic, assign) BOOL isOrderApply;//是否浇筑令审批
@property (nonatomic, strong) NSString *orderApplyUrl;//是否浇筑令审批

@end

@implementation OAApprovalDetailViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"审批详情"];
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"申请表" style:UIBarButtonItemStyleDone target:self action:@selector(applyLookSelector:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    return self;
}

- (void)getPassingParameter:(id)object
{
    if([object isKindOfClass:[NSArray class]]){
        //从审批进入
        NSArray *valueData = object;
        self.viewType = [valueData[1] integerValue];
        NSDictionary *dic = valueData[0];
        self.approvalBaseInfo = dic;
        [self initWithBascInfo:dic];
        
    } else if([object isKindOfClass:[NSString class]]) {
        //从订单详情进入
        self.viewType = 1;
        NSString *serialNumber = (NSString*)object;
        [self getApplyInfoToNet:serialNumber];
    }
    
}

- (void)initWithBascInfo:(NSDictionary*)dic
{
    [self getApplyAllOrders];//获取列表信息
    
    //是否订单类型
    NSString *businessApproval = [self.approvalBaseInfo objectFormatStringForKey:@"businessApproval"];
    self.isOrderApply = [businessApproval isEqualToString:@"SPJZL"];//SPXQ订单审核类型
    if(self.isOrderApply){
        [self getModelPageUrl];//获取模板URL页面URL
        [self getOrderBascInfo];//获取浇筑令模板内容
    } else {
        [self getApplyModeFieldContent];//获取模板内容
    }
    
    NSString *stateStr = @"未知";
    NSInteger mState = [[dic objectFormatStringForKey:@"approvalstate"] integerValue];
    if (mState == 0) stateStr = @"进行中";
    else if (mState == 1) stateStr = @"已通过";
    else if (mState == 2) stateStr = @"未通过";
    else if (mState == 3) stateStr = @"已执行";
    
    NSMutableArray *approval = [NSMutableArray array];
    [self addApprovalInfoKey:@"serialnumber" toKey:@"流  水  号：" defaults:@"未知" format:nil form:dic toArray:approval];
    [self addApprovalInfoKey:@"templatename" toKey:@"审批名称：" defaults:@"未知" format:nil form:dic toArray:approval];
    [self addApprovalInfoKey:@"sponsorid" toKey:@"发  起  人：" defaults:@"未知" format:nil form:dic toArray:approval];
    [self addApprovalInfoKey:@"" toKey:@"审批状态：" defaults:stateStr format:nil form:dic toArray:approval];
    [self addApprovalInfoKey:@"creationTime" toKey:@"发起时间：" defaults:@"未知" format:nil form:dic toArray:approval];
    
    self.approvalData = approval;
    [self.tableView reloadData];
}

- (void)addApprovalInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)applyLookSelector:(id)selector
{
    if(self.isOrderApply){
        //订单审批执行方法
        if(self.orderApplyUrl){
            NSString *orderId = [self.approvalBaseInfo objectFormatStringForKey:@"tableId"];
            NSString *Appurl = [self.orderApplyUrl stringByReplacingOccurrencesOfString:@"{0}"withString:orderId];
            Appurl = [NSString stringWithFormat:@"%@&guid=88C28674-FD9F-4C17-8358-FF26BF70CC2B",Appurl];
            
            OAReadApplyHtmlViewController *view = [[OAReadApplyHtmlViewController alloc] initWithNibUrl:Appurl];
            [self.navigationController pushViewController:view animated:YES];
        } else {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"未找到申请表" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alert.alertViewStyle=UIAlertViewStyleDefault;
            [alert show];
        }
    } else {
        //正常流程执行方法
        NSString *Appurl = [self.approvalBaseInfo objectFormatStringForKey:@"appurl"];
        OAReadApplyHtmlViewController *view = [[OAReadApplyHtmlViewController alloc] initWithNibUrl:Appurl];
        [self.navigationController pushViewController:view animated:YES];
    }
}

- (void)showProgressBar
{
    CGRect viewFrame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height - 64);
    UIView *view = [[UIView alloc] initWithFrame:viewFrame];
    
    //添加进度条
    UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    act.center = CGPointMake(viewFrame.size.width/2, viewFrame.size.height/2);
    act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
    act.hidesWhenStopped = YES;
    [act startAnimating];
    [view addSubview:act];
    
    self.tableView.tableFooterView = view;
}

- (void)showTableViewErrorView:(NSString*)message isAddButtonEvent:(BOOL)eventSatae
{
    //清除所有数据
    [self.approvalData removeAllObjects];
    
    CGRect viewFrame = CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height - 84);
    UIView *view = [[UIView alloc] initWithFrame:viewFrame];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"guess_like_img"]];
    [view addSubview:imageView];
    
    UILabel *lable = [[UILabel alloc] init];
    lable.textAlignment = NSTextAlignmentCenter;
    lable.font = [UIFont systemFontOfSize:15];
    lable.textColor = [UIColor grayColor];
    lable.text = message;
    lable.lineBreakMode = NSLineBreakByWordWrapping;
    lable.numberOfLines = 0;
    [view addSubview:lable];
    
    CGFloat imageViewWidth = imageView.frame.size.width/3*2;
    CGFloat imageViewHeight = imageView.frame.size.height/3*2;
    CGFloat textHeight = [message heightForFont:lable.font andWidth:imageViewWidth + 40];
    
    imageView.frame = CGRectMake(view.frame.size.width/2 - imageViewWidth/2, view.frame.size.height/2 -
                                 imageViewHeight/2 - textHeight/2,imageViewWidth,imageViewHeight);
    lable.frame = CGRectMake(imageView.frame.origin.x - 20, imageView.frame.origin.y + imageViewHeight + 4,
                             imageViewWidth + 40, textHeight);
    
    //判断是否添加按钮事件
    if (eventSatae) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = viewFrame;
        [view addSubview:button];
        [button addTarget:self action:@selector(getApplyAllOrders) forControlEvents:UIControlEventTouchUpInside];
    }
    
    self.tableView.tableFooterView = view;
}


#pragma mark -获取审批信息
- (void)getApplyInfoToNet:(NSString*)serialNumber
{
    //显示进度条
    [self.tableView showCustomProgressOffset:100];
    
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:serialNumber forKey:@"serialNumber"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_MyApplication_SerialNumber" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView hideProgress];//去除进度条
        if(result.resultArray && result.resultArray.count>0){
            NSDictionary *dic = result.resultArray.firstObject;
            self.approvalBaseInfo = dic;
            [self initWithBascInfo:dic];
        } else {
            [self.tableView setTableViewNotDataDrawText:@"暂无审批信息" isShow:YES];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self.tableView setTableViewNotDataDrawText:@"哦，出错了" isShow:YES];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self.tableView setTableViewNotDataDrawText:@"网络异常" isShow:YES];
    }];
}

#pragma mark -获取模版URL页面

- (void)getModelPageUrl
{
    //获取用户登录信息
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:@"SPJZL" forKey:@"approvalType"];//订单审批类型
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_ApprovalType" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(result.resultArray && result.resultArray.count>0){
            NSDictionary *mDictionary = result.resultArray.firstObject;
            self.orderApplyUrl = [mDictionary objectFormatStringForKey:@"PageUrl"];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
    }];
    
}

#pragma mark -获取浇筑令审批的模块信息

- (void)getOrderBascInfo
{
    NSString *orderId = [self.approvalBaseInfo objectFormatStringForKey:@"tableId"];
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"OA_APPLY_ORGER_INFO"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"订单ID" value:orderId];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            self.appleModeData = [self appleOrderModelFiledHanleArray:firstArray];
            self.appleContentState = 3;
            [self.tableView reloadData];
        } else {
            //未找到数据
            self.appleContentState = 1;
            [self.tableView reloadData];
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.appleContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.appleContentState = 2;
        [self.tableView reloadData];
        
    }];
}

- (NSMutableArray*)appleOrderModelFiledHanleArray:(NSArray*)array
{
    NSMutableArray *approval = [NSMutableArray array];
    if(array && array.count > 0){
        NSDictionary *dictionary = array.firstObject;
        for (NSString *key in dictionary) {
            NSString *keyString = [NSString stringWithFormat:@"%@：", key];
            NSDictionary *valueDic = [NSDictionary dictionaryWithObject:dictionary[key] forKey:keyString];
            [approval addObject:valueDic];
        }
    }
    return approval;
}

#pragma mark -获取审批下所有节点

- (void)getApplyAllOrders
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSString *serialNumber = [self.approvalBaseInfo objectFormatStringForKey:@"serialnumber"];
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:serialNumber forKey:@"serialNumber"];
    
    //如果是我的审批，则需要用户ID
    if (self.viewType == 2) [model setValue:userInfo.Id forKey:@"userid"];
    else [model setValue:@0 forKey:@"userid"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_getApproval_flowNodes" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(result.resultArray && result.resultArray.count>0){
            self.orderData = result.resultArray;
            self.orderContentState = 3;
            [self.tableView reloadData];
        } else {
            self.orderContentState = 1;
            [self.tableView reloadData];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
    }];
}

- (void)getApplyModeFieldContent
{
    NSString *serialNumber = [self.approvalBaseInfo objectFormatStringForKey:@"serialnumber"];
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:serialNumber forKey:@"serialNumber"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_Get_TemplateField" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(result.resultArray && result.resultArray.count>0){
            self.appleModeData = [self appleModelFiledHanleArray:result.resultArray];
            self.appleContentState = 3;
            [self.tableView reloadData];
        } else {
            self.appleContentState = 1;
            [self.tableView reloadData];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.appleContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.appleContentState = 2;
        [self.tableView reloadData];
    }];
    
}

- (NSMutableArray*)appleModelFiledHanleArray:(NSArray*)array
{
    NSMutableArray *approval = [NSMutableArray array];
    for (NSDictionary *dictionary in array) {
        NSString *titleString = [NSString stringWithFormat:@"%@：",[dictionary objectFormatStringForKey:@"fieldchname"]];
        [self addApprovalInfoKey:@"fieldvalue" toKey:titleString defaults:@"未知" format:nil form:dictionary toArray:approval];
    }
    
    return approval;
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(self.approvalData && self.approvalData.count>0) return 4;
    else return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if(section == 1) {
        return 1;
        
    } else if(section == 2){
        NSArray *file = [self.approvalBaseInfo objectForKey:@"fjlist"];
        if([file isKindOfClass:[NSArray class]] && file.count>0) return file.count;
        else return 1;
        
    }else if(section == 3){
        if(self.orderContentState == 0) return 1;
        else if(self.orderContentState == 1) return 1;
        else if(self.orderContentState == 2) return 1;
        else if(self.orderContentState == 3) return self.orderData.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AutoTextTableViewCell"];
        [cell setDataArray:self.approvalData];
        return cell;
        
    } else if(indexPath.section == 1){
        if (self.appleContentState == 3) {
            AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AutoTextTableViewCellApple"];
            [cell setDataArray:self.appleModeData];
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicatss"];
            cell.contentView.frame = CGRectMake(0, 0, cell.contentView.frame.size.width, 54);
            
            if(self.appleContentState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 27.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.appleContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.center = CGPointMake(SuperWidth/2, cell.contentView.frame.size.height/2);
                label.text = @"未找到审批模板内容";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.appleContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.center = CGPointMake(SuperWidth/2, cell.contentView.frame.size.height/2);
                label.text = @"加载失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
        
    } else if(indexPath.section == 2){
        NSArray *file = [self.approvalBaseInfo objectForKey:@"fjlist"];
        if([file isKindOfClass:[NSArray class]] && file.count>0) {
            DownFileInfoCell *cell = [[DownFileInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicatFile"];
            NSDictionary *fileDictionary = [file objectAtIndex:indexPath.row];
            cell.fileName.text = [fileDictionary objectFormatStringForKey:@"attname"];
            cell.fileSize.text = [fileDictionary objectFormatStringForKey:@"fileSize"];
            cell.iconImageView.image = [FileTypeIcon setFileTypeIcon:[fileDictionary objectFormatStringForKey:@"attname"]];
            
            cell.downButton.userInteractionEnabled = YES;
            cell.downButton.tag = indexPath.row;
            [cell.downButton addTarget:self action:@selector(downadjunctFile:) forControlEvents:UIControlEventTouchUpInside];
                
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicatFile"];
            cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 44);
            
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"无附件";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        return nil;
        
    } else if(indexPath.section == 3){
        if (self.orderContentState == 3) {
            
            static NSString *TableSampleIdentifiers = @"TableSampleIdentifierSPYJ";
            OAApprovalDetailViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableSampleIdentifiers];
            if (cell == nil)
                cell = [[OAApprovalDetailViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifiers];
            
            NSDictionary *mDictionary = [self.orderData objectAtIndex:indexPath.row];
            
            //批状态0-进行中1-通过2-不通过3-执行
            NSInteger mState = [[mDictionary objectFormatStringForKey:@"approvalstate"] integerValue];
            if (mState == 0) cell.spztLable.hidden = YES;
            else if (mState == 1) cell.spztLable.text = @"同意";
            else if (mState == 2) cell.spztLable.text = @"不同意";
            else if (mState == 3) cell.spztLable.text = @"执行";
            
            //如果已审批，显示审批人，否则显示职位
            if(mState != 0) cell.spdxLable.text =[mDictionary objectFormatForKey:@"reviseid"];
            else cell.spdxLable.text =[mDictionary objectFormatForKey:@"tnodename"];
            
            //标记背景及审批提示
            cell.incoNumberLable.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
            if(mState == 0){
                cell.markBgLable.backgroundColor = [UIColor lightGrayColor];
                cell.sfspLable.text = @"未审批";
            } else if(mState == 1){
                cell.markBgLable.backgroundColor = [UIColor colorWithRed:24/255.0 green:159/255.0 blue:151/255.0 alpha:0.85];
                cell.sfspLable.text = @"已审批";
            } else if(mState == 2){
                cell.markBgLable.backgroundColor = [UIColor colorWithRed:242/255.0 green:80/255.0 blue:23/255.0 alpha:1.0];
                cell.sfspLable.text = @"已拒绝";
            } else if(mState == 3){
                cell.markBgLable.backgroundColor = [UIColor colorWithRed:24/255.0 green:159/255.0 blue:151/255.0 alpha:0.85];
                cell.sfspLable.text = @"已执行";
            }
            
            //判断该节点是否可以审批
            BOOL isSP = [[mDictionary objectFormatForKey:@"keshengp"] boolValue];
            if (!isSP) {
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.userInteractionEnabled = NO;
            } else {
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
                cell.markBgLable.backgroundColor = [UIColor colorWithRed:255/255.0 green:128/255.0 blue:0/255.0 alpha:0.75];
                cell.sfspLable.text = @"我要审批";
            }
            
            //未审批节点处理
            cell.incoNumberLable.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
            if(mState == 0){
                cell.spsjLable.text = @"暂无";
                cell.qsyjLable.text = @"暂无";
                
                //添加分割线
                UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 73, SuperWidth, 1)];
                lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
                [cell.contentView addSubview:lineView];
                
            } else {
                cell.spsjLable.text = [mDictionary objectFormatForKey:@"revisetime"];
                NSString *qsyj = [mDictionary objectFormatStringForKey:@"affixTo"];
                cell.qsyjLable.text = qsyj;
            }
            
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicat"];
            cell.contentView.frame = CGRectMake(0, 0, cell.contentView.frame.size.width, 54);
            
            if(self.orderContentState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(cell.frame.size.width/2, 27.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"未找到审批节点";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if (section == 0) {
        lable.text = @"审批明细";
    } else if (section == 1) {
        lable.text = @"审批模板内容";
    } else if (section == 2) {
        lable.text = @"附件列表";
    } else if(section == 3){
        lable.text = @"审批结果";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.approvalData];
        return cell.contentView.frame.size.height;
        
    } else if (indexPath.section == 1) {
        if(self.appleContentState == 3){
            AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
            [cell setDataArray:self.appleModeData];
            return cell.contentView.frame.size.height;
        } else return 54;
        
    } else if(indexPath.section == 2){
        NSArray *file = [self.approvalBaseInfo objectForKey:@"fjlist"];
        if([file isKindOfClass:[NSArray class]] && file.count>0) return 54;
        else return 44;
    } else if(indexPath.section == 3){
        if(self.orderContentState == 3) {
            NSDictionary *mDictionary = [self.orderData objectAtIndex:indexPath.row];
            NSInteger mState = [[mDictionary objectFormatStringForKey:@"approvalstate"] integerValue];
            if(mState != 0){
                NSString *qsyj = [mDictionary objectFormatStringForKey:@"affixTo"];
                CGFloat textSize = [qsyj heightAutoCalculateFontSize:[UIFont systemFontOfSize:14] andWidth:143+(SuperWidth-320)];
                return textSize < 17 ? 74 : (74 + textSize - 17);
            } else return 74;
        } else return 54;
    }
    
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 1 && self.appleContentState == 2){
        //加载失败执行
        self.appleContentState = 0;
        [self.tableView reloadData];
        if(self.isOrderApply){
            [self getOrderBascInfo];//获取浇筑令模板内容
        } else {
            [self getApplyModeFieldContent];//获取模板内容
        }
        
    } else if(indexPath.section == 2) {
        //预览文件
        NSArray *file = [self.approvalBaseInfo objectForKey:@"fjlist"];
        if([file isKindOfClass:[NSArray class]] && file.count>0) {
            NSDictionary *fileDictionary = [file objectAtIndex:indexPath.row];
            NSString *fileName = [fileDictionary objectFormatStringForKey:@"attname"];
            NSString *filePath = [fileDictionary objectFormatStringForKey:@"attpath"];
            //创建连接，预览文件
            PreviewFileHelper *preview = [[PreviewFileHelper alloc] init];
            [preview startPreviewExternalFile:filePath fileName:fileName];
        }
        
    } else if(indexPath.section == 3){
        if (self.orderContentState == 3){
            //发起审批
            NSDictionary *nowNodeModel = [self.orderData objectAtIndex:indexPath.row];
            
            //当为最后节点审批的时候
            NSDictionary *nextNodeModel = [NSDictionary dictionary];
            if (indexPath.row < self.orderData.count - 1)
                nextNodeModel = [self.orderData objectAtIndex:indexPath.row + 1];
            
            NSArray *valueArray = @[self.approvalBaseInfo,nowNodeModel,nextNodeModel];
            OAApprovalSubmitViewController *viewController = [[OAApprovalSubmitViewController alloc] initWithValue:valueArray];
            viewController.backResultDelagate = self;
            [self.navigationController pushViewController:viewController animated:YES];
            
        } else if (self.orderContentState == 2) {
            self.orderContentState = 0;
            [self.tableView reloadData];
            [self getApplyAllOrders];
        }
        
    }
}

#pragma mark Button Event

- (void)downadjunctFile:(UIButton*)button
{
    //下载附件
    NSArray *file = [self.approvalBaseInfo objectForKey:@"fjlist"];
    if([file isKindOfClass:[NSArray class]] && file.count>0) {
        NSDictionary *fileDictionary = [file objectAtIndex:button.tag];
        NSString *fileName = [fileDictionary objectFormatStringForKey:@"attname"];
        NSString *filePath = [fileDictionary objectFormatStringForKey:@"attpath"];
        //创建连接，下载文件
        DownLoadHandle *downLoad = [[DownLoadHandle alloc] init];
        [downLoad startDownExternalFile:filePath fileName:fileName];
    }
}

#pragma mark
#pragma mark BackResultDataDelagate

- (void) backResultDataKey:(id)key dataValue:(id)backValue
{
    if(self.backResultDelagate)
        [self.backResultDelagate backResultDataKey:self.key dataValue:nil];
    [self.navigationController popViewControllerAnimated:YES];
}


@end
